<template>
  <t-form ref="form" :class="['item-container', `login-${type}`]" :data="formData" :rules="FORM_RULES" label-width="0"
    @submit="onSubmit">
    <template v-if="type == 'password'">
      <t-form-item name="account">
        <t-input v-model="formData.account" size="large" placeholder="请输入账号">
          <template #prefix-icon>
            <t-icon name="user" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item name="password">
        <t-input v-model="formData.password" size="large" :type="showPsw ? 'text' : 'password'" clearable key="password"
          placeholder="请输入登录密码">
          <template #prefix-icon>
            <t-icon name="lock-on" />
          </template>
          <template #suffix-icon>
            <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
          </template>
        </t-input>
      </t-form-item>

      <div class="check-container remember-pwd">
        <t-checkbox v-model="remember">记住账号</t-checkbox>
        <span class="tip">忘记账号？</span>
      </div>
    </template>

    <!-- 扫码登陆 -->
    <!--    <template v-else-if="type == 'qrcode'">
      <div class="tip-container">
        <span class="tip">请使用微信扫一扫登录</span>
        <span class="refresh">刷新 <t-icon name="refresh" color="#0052D9" /> </span>
      </div>
      <qrcode-vue value="" :size="192" level="H" />
    </template> -->

    <!-- 手机号登陆 -->
    <template v-else>
      <t-form-item name="phone">
        <t-input v-model="formData.phone" size="large" placeholder="请输入您的手机号">
          <template #prefix-icon>
            <t-icon name="user" />
          </template>
        </t-input>
      </t-form-item>

      <t-form-item class="verification-code" name="verifyCode">
        <t-input v-model="formData.verifyCode" size="large" placeholder="请输入验证码" key="verifyCode" />
        <t-button variant="outline" :disabled="countDown > 0" @click="sendVeri">
          {{ countDown == 0 ? '发送验证码' : `${countDown}秒后可重发` }}
        </t-button>
      </t-form-item>
    </template>

    <t-form-item v-if="type !== 'qrcode'" class="btn-container">
      <t-button block size="large" type="submit">登录</t-button>
    </t-form-item>

    <div class="switch-container">
      <span v-if="type !== 'password'" class="tip" @click="switchType('password')">使用账号密码登录</span>
      <!-- <span v-if="type !== 'qrcode'" class="tip" @click="switchType('qrcode')">使用微信扫码登录</span> -->
      <span v-if="type !== 'phone'" class="tip" @click="switchType('phone')">使用手机号登录</span>
    </div>
  </t-form>
</template>
<script lang="ts">
  import Vue from 'vue';
  import QrcodeVue from 'qrcode.vue';

  const INITIAL_DATA = {
    phone: '',
    account: 'admin',
    password: 'admin',
    verifyCode: '',
    checked: false
  };

  const FORM_RULES = {
    phone: [{
      required: true,
      message: '手机号必填',
      type: 'error'
    }],
    account: [{
      required: true,
      message: '账号必填',
      type: 'error'
    }],
    password: [{
      required: true,
      message: '密码必填',
      type: 'error'
    }],
    verifyCode: [{
      required: true,
      message: '验证码必填',
      type: 'error'
    }]
  };
  /** 高级详情 */
  export default Vue.extend({
    name: 'Login',
    components: {
      QrcodeVue
    },
    data() {
      return {
        FORM_RULES,
        type: 'password',
        formData: {
          ...INITIAL_DATA
        },
        showPsw: false,
        countDown: 0,
        intervalTimer: null,
        remember: false,
        veriDisable: false,
        interval: '',
        veriCode: '',
      };
    },
    beforeDestroy() {
      clearInterval(this.intervalTimer);
      window.clearInterval(this.interval)
    },
    methods: {
      async sendVeri() {
        if (this.formData.phone == '') {
          this.$message.error("请输入手机号！")
          return
        }
        await this.$request
          .post('/send-verify?phone=' + this.formData.phone)
          .then(async res => {
            console.log(res);
            if (res.code === 0) {
              this.$message.success('验证码已发送！有效期一小时');
              this.veriCode = res.veriCode;
              this.exceed = new Date(new Date().getTime() + 1 * 60 * 60 * 1000).getTime();
              let me = this;
              me.veriDisable = true;
              me.countDown = 60
              this.interval = window.setInterval(function() {
                me.countDown--;
                if (me.countDown < 0) {
                  me.veriNotice = '发送验证码';
                  me.veriDisable = true;
                  me.countDown = 60;
                  window.clearInterval(interval);
                }
              }, 1000);
            } else {
              this.$message.error('发送验证码失败！请稍后再试');
            }
          })
          .catch(e => {
            this.$message.error('发送验证码失败！请稍后再试');
            console.log(e);
          })
          .finally(() => {});
      },
      switchType(val) {
        this.type = val;
        this.$refs.form.reset();
      },
      async onSubmit({
        validateResult
      }) {
        if (validateResult === true && this.type == 'password') {
          console.log('rua');
          await this.$request
            .post('/doctor-login?type=password', {
              phone: this.formData.account,
              password: this.formData.password
            })
            .then(async res => {
              if (res.code === 0) {
                console.log(res);
                this.$store.commit('user/setToken', res.token);
                this.$store.commit('user/setUserInfo', res.info);
                this.$message.success('登录成功');
                await this.$store.dispatch('permission/initRoutes', this.$store.getters['user/roles']);
                console.log('to dashboard');
                if (this.remember) {
                  localStorage.setItem('ovcf-token', res.token);
                  localStorage.setItem('info', JSON.stringify(this.$store.state.user.userInfo));
                }
                this.$router.replace('/').catch(() => '');
              } else {
                this.$message.error('登录失败！请检查账号密码或找回密码');
              }
            })
            .catch(e => {
              this.$message.error('登陆错误 请重试')
              console.log(e);
            })
            .finally(() => {});
        } else if (validateResult === true && this.type == "phone") {
          if (this.formData.verifyCode == this.veriCode) {
            await this.$request
              .post('/doctor-login?type=phone', {
                phone: this.formData.phone
              })
              .then(async res => {
                if (res.code === 0) {
                  console.log(res);
                  this.$store.commit('user/setToken', res.token);
                  this.$store.commit('user/setUserInfo', res.info);
                  this.$message.success('登录成功');
                  await this.$store.dispatch('permission/initRoutes', this.$store.getters['user/roles']);
                  console.log('to dashboard');
                  if (this.remember) {
                    localStorage.setItem('ovcf-token', res.token);
                    localStorage.setItem('info', JSON.stringify(this.$store.state.user.userInfo));
                  }
                  this.$router.replace('/').catch(() => '');
                } else {
                  this.$message.error('登录失败！请检查账号是否存在');
                }
              })
              .catch(e => {
                this.$message.error('登陆错误 请重试')
                console.log(e);
              })
              .finally(() => {});
          }
        }
      },
      handleCounter() {
        this.countDown = 60;
        this.intervalTimer = setInterval(() => {
          if (this.countDown > 0) {
            this.countDown -= 1;
          } else {
            clearInterval(this.intervalTimer);
            this.countDown = 0;
          }
        }, 1000);
      }
    }
  });
</script>
